package edu.jmu.action.privilege;


import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import edu.jmu.bean.privilege.Privilege;
import edu.jmu.bean.privilege.Role;
import edu.jmu.bean.system.OperateLog;
import edu.jmu.service.sysmanage.OperateLogService;
import edu.jmu.utils.GenericsUtils;
import edu.jmu.utils.WebUtil;


@Aspect	@Component
public class Interceptor {
	
	@Resource
	OperateLogService operateLogService;
	
	/**
	 * 定义切面
	 */
	@SuppressWarnings("unused")
	@Pointcut(" execution(java.lang.String edu.jmu.action..*.*()) && " + 
			  "!execution(java.lang.String edu.jmu.action..*.set*()) && " + 
			  "!execution(java.lang.String edu.jmu.action..*.get*())")
	private void intercepterMethod(){}
	
	@Around("intercepterMethod()")
	public Object doActionClassProfilling(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {	
		Object returnValue = null;
		Privilege privilege = GenericsUtils.getMethodPermission(proceedingJoinPoint.getTarget().getClass(),proceedingJoinPoint.getSignature().getName());
		
		//没有获得注解  即不需要权限-- 则直接运行
		if( privilege == null || "".equals(privilege)){
			returnValue = proceedingJoinPoint.proceed();
		}else{
			boolean noPass = true;
			for(Role role : WebUtil.getUser().getRoles()){
				for(Privilege myPrivilege : role.getPrivileges()){
					if(myPrivilege.getModule().equals(privilege.getModule()) && myPrivilege.getPrivilege().equals(privilege.getPrivilege())){
						returnValue = proceedingJoinPoint.proceed();
						OperateLog log = new OperateLog();
						log.setUser(WebUtil.getUser());
						log.setOperateName(privilege.getPrivilege());
						log.setOperateObject(privilege.getModule());
						log.setOperateDesc(privilege.getDesc());
						operateLogService.save(log);
						noPass = false;
						break;
					}
				}
				if(!noPass)	break;
			}		
			if(noPass){
				ServletActionContext.getResponse().sendRedirect("/oa/error.html");
			}
		}		
		return returnValue;
	}
}
